package wxpay

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/json"
	"errors"
)

type MchNative struct {
	WxPayMch
}

func NewMchNative(mchid, appid, mch_api_key string, pem_cert *x509.Certificate, pem_key *rsa.PrivateKey) *MchNative {
	ent := &MchNative{}
	ent.Appid = appid
	ent.Mchid = mchid
	ent.MchAPIKey = mch_api_key
	ent.MchPrivateKey = pem_key
	ent.MchCertificate = pem_cert
	return ent
}

//支付统一下单
func (ent *MchNative)CreateOrder(data NativeOrderData) (string, error)  {
	var preq NativeOrderCreateReq
	preq.Appid = ent.Appid
	preq.Mchid = ent.Mchid
	preq.NativeOrderData = data
	preq.Sp_appid = ""
	preq.Sp_mchid = ""
	preq.NativeOrderData.Sub_mchid = ""
	preq.NativeOrderData.Sub_appid = ""
	data_body, _ := json.Marshal(preq)

	var pret NativeOrderCreateRet
	const url = "https://api.mch.weixin.qq.com/v3/pay/transactions/native"
	result, err := WxPayPostV3(&ent.MchParam, url, data_body)
	if err != nil {
		return "", err
	}

	err = json.Unmarshal([]byte(result), &pret)
	if err != nil {
		return "", err
	}
	if pret.Code_url == "" {
		return "", errors.New(pret.Return_msg)
	}

	return pret.Code_url, nil
}
